import React, { useEffect, useState } from "react";
import * as S from "./style";
import formatPrice from "/src/utils/formatPrice";

const Product = ({
  product: {
    sku,
    title,
    price,
    installments,
    currencyId,
    currencyFormat,
    isFreeShipping,
  },
}) => {
  const [defaultImage, setDefaultImage] = useState("");
  const [hoverImage, setHoverImage] = useState("");
  useEffect(() => {
    import(`/src/static/products/${sku}-1-product.webp`).then((img) =>
      setDefaultImage(img.default)
    );
    import(`/src/static/products/${sku}-2-product.webp`).then((img) =>
      setHoverImage(img.default)
    );
  }, [sku]);

  const formattedPrice = formatPrice(price, currencyId);
  let productInstallment;

  if (installments) {
    const installmentPrice = price / installments;

    productInstallment = (
      <S.Installment>
        <span>or {installments} x </span>
        <b>
          {currencyFormat}
          {formatPrice(installmentPrice, currencyId)}
        </b>
      </S.Installment>
    );
  }
  return (
    <S.Container>
      {isFreeShipping && <S.Stopper>Free shipping</S.Stopper>}
      <S.Image
        alt={title}
        style={{
          "--defaultImage": `url(${defaultImage})`,
          "--hoverImage": `url(${hoverImage})`,
        }}
      />
      <S.Title>{title}</S.Title>
      <S.Price>
        <S.Val>
          <small>{currencyFormat}</small>
          <b>{formattedPrice.substring(0, formattedPrice.length - 3)}</b>
          <span>{formattedPrice.substring(formattedPrice.length - 3)}</span>
        </S.Val>
        {productInstallment}
      </S.Price>
      <S.BuyButton>Add to cart</S.BuyButton>
    </S.Container>
  );
};

export default Product;
